//
//  SVCommon.m
//  ShortVideo-ccinon
//
//  Created by LIN TONG on 2017/7/5.
//  Copyright © 2017年 LIN TONG. All rights reserved.
//

#import "SVCommon.h"
#import "SVConfig.h"
#import "SVAPIReqeust.h"
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <ProgressHUD.h>
#import <MediaPlayer/MediaPlayer.h>

@implementation SVCommon
+ (NSString *)getClientUUID
{
#if TARGET_IPHONE_SIMULATOR
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uuid = [userDefaults objectForKey: SV_USER_UUID];
    if (uuid == nil || [uuid isEqualToString:@""]) {
        uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [SVCommon saveClientUUID:uuid];
    }
#else
    NSString *uuid = [JNKeychain loadValueForKey: SV_USER_UUID];
    if([uuid length] == 0){
        uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [SVCommon saveClientUUID:uuid];
    }
#endif
    return uuid;
}

+ (void)saveClientUUID:(NSString *)uuid
{
#if TARGET_IPHONE_SIMULATOR
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject: uuid forKey: SV_USER_UUID];
#else
    [JNKeychain saveValue: uuid forKey: SV_USER_UUID];
#endif
}

+ (void)uploadVideoInPath:(NSString *)path qrID:(NSInteger)qrid updateProgress:(void(^)(float progress))updateBlock completionBlock:(void(^)(BOOL success,NSString *objectKey,NSString *endPoint,NSString *buketName))completionBlock{
    [SVAPIReqeust svRequestAPI:API(@"/mct/vod/video/getObjectKey") method:@"GET" parametors:@{@"type":@"video",@"vod_qr_id":[NSString stringWithFormat:@"%ld",qrid]} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
        if(success){
            //请求获取object key
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                NSString *objectKey = [NSString stringWithFormat:@"%@.mp4",[data objectForKey:@"data"]];
                if(objectKey && objectKey.length){
                    /***********************************
                     STS获取token,以及加密后的Secret Key,ID
                     ***********************************/
                    
                    id<OSSCredentialProvider> credential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
                        // 构造请求访问您的业务server
                        NSMutableDictionary *header = [NSMutableDictionary dictionary];
                        [header setObject:[NSString stringWithFormat:@"iPhone %@",[UIDevice currentDevice].systemVersion] forKey:@"X-AGENT"];
                        [header setObject:[SVCommon getClientUUID] forKey:@"X-UUID"];
                        NSString *token = [JNKeychain loadValueForKey:SV_USER_TOKEN];
                        if(token && [token length]>0){
                            [header setObject:token forKey:@"X-TOKEN"];
                        }else{
                            [header setObject:@"" forKey:@"X-TOKEN"];
                        }
                        
                        NSURL * url = [NSURL URLWithString:API(@"/mct/vod/video/doaction")];
                        ASIHTTPRequest *asiRequest = [[ASIHTTPRequest alloc]initWithURL:url];
                        [asiRequest setRequestMethod:@"GET"];
                        asiRequest.useCookiePersistence = NO;
                        asiRequest.requestHeaders = header;
                        
                        __weak ASIHTTPRequest *request = asiRequest;
                        
                        [asiRequest setStartedBlock:^{
                            NSLog(@"开始请求");
                        }];
                        
                        [asiRequest setFailedBlock:^{
                            NSLog(@"请求失败!%@",request.error);
                        }];
                        
                        [asiRequest setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {
                            
                            NSLog(@"%@",request.responseHeaders);
                            NSString *token = [responseHeaders objectForKey:@"X-TOKEN"];
                            if(token && [token length]>0){
                                [JNKeychain saveValue:token forKey:SV_USER_TOKEN];
                            }
                        }];
                        
                        [asiRequest startSynchronous];
                        
                        NSString *json = [request responseString];
                        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
                        NSError *err;
                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                             
                                                                            options:NSJSONReadingMutableContainers
                                             
                                                                              error:&err];
                        if(!err){
                            // 返回数据是json格式，需要解析得到token的各个字段
                            OSSFederationToken * token = [OSSFederationToken new];
                            token.tAccessKey = [[[dic objectForKey:@"data"]objectForKey:@"Credentials"]objectForKey:@"AccessKeyId"];
                            token.tSecretKey = [[[dic objectForKey:@"data"]objectForKey:@"Credentials"]objectForKey:@"AccessKeySecret"];
                            token.tToken = [[[dic objectForKey:@"data"]objectForKey:@"Credentials"]objectForKey:@"SecurityToken"];
                            token.expirationTimeInGMTFormat = [[[dic objectForKey:@"data"]objectForKey:@"Credentials"]objectForKey:@"Expiration"];
                            NSLog(@"get token: %@", token);
                            return token;
                        }else{
                            NSLog(@"get token error: %@", err);
                            return nil;
                        }
                    }];
                    
                    
                    NSString *endPoint = @"oss-cn-hangzhou.aliyuncs.com";
                    OSSClient *client = [[OSSClient alloc]initWithEndpoint:endPoint credentialProvider:credential2];
                    
                    /********
                     初始化上传
                     ********/
                    
                    __block NSString * uploadId = nil;
                    __block NSMutableArray * partInfos = [NSMutableArray new];
                    NSString * uploadToBucket = @"video-storage-01";
                    NSString * uploadObjectkey = objectKey;
                    OSSInitMultipartUploadRequest * init = [OSSInitMultipartUploadRequest new];
                    init.bucketName = uploadToBucket;
                    init.objectKey = uploadObjectkey;
                    //init.contentType = @"video/mpeg4";
                    OSSTask * initTask = [client multipartUploadInit:init];
                    [initTask waitUntilFinished];
                    if (!initTask.error) {
                        OSSInitMultipartUploadResult * result = initTask.result;
                        uploadId = result.uploadId;
                    } else {
                        NSLog(@"multipart upload failed, error: %@", initTask.error);
                        return;
                    }
                    
                    
                    /**********
                     开始分片上传
                     **********/
                    
                    uint64_t fileSize = [[[[NSFileManager defaultManager]attributesOfItemAtPath:path error:nil]objectForKey:NSFileSize]unsignedLongLongValue];;
                    //要上传的文件
                    int chuckCount = ceil(floor(fileSize)/500000.0f);
                    //分片上传数量
                    uint64_t offset = 500000;
                    //分片大小
                    for (int i = 1; i <= chuckCount; i++) {
                        OSSUploadPartRequest * uploadPart = [OSSUploadPartRequest new];
                        uploadPart.bucketName = uploadToBucket;
                        uploadPart.objectkey = uploadObjectkey;
                        uploadPart.uploadId = uploadId;
                        uploadPart.partNumber = i; // part number start from 1
                        NSFileHandle* readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
                        [readHandle seekToFileOffset:offset * (i -1)];
                        NSData* data = [readHandle readDataOfLength:offset];
                        uploadPart.uploadPartData = data;
                        OSSTask * uploadPartTask = [client uploadPart:uploadPart];
                        [uploadPartTask waitUntilFinished];
                        if (!uploadPartTask.error) {
                            OSSUploadPartResult * result = uploadPartTask.result;
                            uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:uploadPart.uploadPartFileURL.absoluteString error:nil] fileSize];
                            [partInfos addObject:[OSSPartInfo partInfoWithPartNum:i eTag:result.eTag size:fileSize]];
                            
                            float progress = (float)i/(float)chuckCount;
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                updateBlock(progress);
                            });
                        } else {
                            NSLog(@"upload part error: %@", uploadPartTask.error);
                            return;
                        }
                    }
                    
                    
                    /**********
                     完成分片上传
                     **********/
                    OSSCompleteMultipartUploadRequest * complete = [OSSCompleteMultipartUploadRequest new];
                    complete.bucketName = uploadToBucket;
                    complete.objectKey = uploadObjectkey;
                    complete.uploadId = uploadId;
                    complete.partInfos = partInfos;
                    OSSTask * completeTask = [client completeMultipartUpload:complete];
                    [[completeTask continueWithBlock:^id(OSSTask *task) {
                        if (!task.error) {
                            OSSCompleteMultipartUploadResult * result = task.result;
                            // ...
                        } else {
                            // ...
                        }
                        return nil;
                    }] waitUntilFinished];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completionBlock(YES,objectKey,endPoint,uploadToBucket);
                    });
                    
                }
            });
       }
    }];
}

+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = NO;
    
    CMTime time = CMTimeMakeWithSeconds(2.0, 600);
    
    NSError *error = nil;
    
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    
    UIImage *thumbImg = [[UIImage alloc] initWithCGImage:image];
    
    return thumbImg;
}
@end
